package it.datagraf.formazione.hellostruts.dao;

import it.datagraf.formazione.hellostruts.entity.CurriculumVitae;
import java.sql.SQLException;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

public class CurriculumVitaeDaoHbm implements CurriculumVitaeDaoI {

	private SessionFactory sessionFactory;

    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }
    
	@Override
	public List<CurriculumVitae> list() {
		Session s=sessionFactory.getCurrentSession();
		return s.createQuery("from CurriculumVitae").list();
	}

	@Override
	public void insertCV(CurriculumVitae cv) throws SQLException {
		this.sessionFactory.getCurrentSession().saveOrUpdate(cv);
		
	}

	@Override
	public void remove(long id) throws SQLException {
		Long idI=new Long(id);
		CurriculumVitae cv=find(idI.intValue());
		this.sessionFactory.getCurrentSession().delete(cv);
	}

	@Override
	public List<CurriculumVitae> listCvs_ricerca(String Cognome, String Nome,
			String eta) throws SQLException {
		// TODO Auto-generated method stub///////////////////////////////////////////////////////////////////////////////////////////////////////DA FARE
		return null;
	}

	@Override
	public int findId(String owner) throws SQLException {
		CurriculumVitae cv =(CurriculumVitae) this.sessionFactory.getCurrentSession().createQuery("from CurriculumVitae where owner= :own").setParameter("own", owner).uniqueResult();
		if(cv==null)
			return -1;
		Long idI=new Long(cv.getId());
		return idI.intValue();
	}

	@Override
	public CurriculumVitae find(int id) throws SQLException {
		Long idI = new Long(id);
		return (CurriculumVitae) this.sessionFactory.getCurrentSession().createQuery("from CurriculumVitae where id= :cv_id").setParameter("cv_id", idI).uniqueResult();
	}

	@Override
	public CurriculumVitae find(CurriculumVitae cv) throws SQLException {
		Long idI=new Long(cv.getId());
		return find(idI.intValue());
	}

	@Override
	public void update(CurriculumVitae cv) throws SQLException {
		Session session=this.sessionFactory.getCurrentSession();
		if(session ==null)
			session = this.sessionFactory.openSession();
		else
			session.clear();
		
		session.update(cv);
		session.flush();
		
		
	}


	@Override
	public void closeConnection() {
		// TODO Auto-generated method stub
		
	}
	

}
